<template>
  <div id="trainingKnowledgeList">
    <Splitpanes class="area">
      <Pane size="20">
        <vxe-toolbar perfect>
          <template #buttons>
            <vxe-button type="text" icon="vxe-icon-refresh" class="button-blue" content="刷新" @click="getKnowledgeList" :loading="showKnowledgeLoading"></vxe-button>
          </template>
        </vxe-toolbar>
        <div class="trainingBox">
          <vxe-table ref="trainingUserTableRef" :loading="showKnowledgeLoading" class="mytable-scrollbar" @current-change="currentChangeEvent" border align="left" height="auto" :keep-source="true" :data="knowledgeList" :row-config="{ isCurrent: true, isHover: true }" resizable show-overflow>
            <vxe-column type="seq" title="序号" align="center" width="30"></vxe-column>
            <vxe-column field="code" title="编码"></vxe-column>
            <vxe-column field="name" title="名称"> </vxe-column>
          </vxe-table>
        </div>
      </Pane>
      <Pane size="20"
        ><el-scrollbar style="height: 100%">
          <el-tree ref="leftTree" :data="knowledgeCatalogAndContentTreeData" v-loading="showTreeLoading" :props="defaultProps" @node-click="handleNodeClick" class="tools-tree" node-key="id" default-expand-all highlight-current :current-node-key="currentTreeNode.id">
            <template #default="{ data }">
              <span
                ><img :src="'../../../src/assets/images/Knowledge/' + data.knType + '.png'" style="width: 15px; height: 15px; margin-right: 10px" />
                <div style="float: right">
                  {{ data.name }}
                </div>
              </span>
            </template>
          </el-tree>
        </el-scrollbar>
      </Pane>
      <Pane size="60">
        <vxe-table ref="trainingTableRef" :loading="showTrainLoading" class="mytable-scrollbar" border align="left" height="auto" :keep-source="true" :data="trainingList" :row-config="{ isCurrent: true, isHover: true }" :column-config="{resizable: true}" show-overflow>
          <vxe-column type="seq" title="序号" align="center" width="30"></vxe-column>
          <vxe-column field="trainingName" title="培训主题" width="180">
            <template #default="{ row }">
              <router-link :to="{ path: '/trainingview', query: { param1: row.id, param3: 'thirdTab' } }">
                <a href="">{{ row.trainingName }}</a>
              </router-link>
            </template>
          </vxe-column>
          <vxe-column field="trainingDate" title="培训时间" width="130"></vxe-column>
          <vxe-column field="address" title="培训地点" width="100"> </vxe-column>
          <vxe-column field="endDate" title="培训结束时间" width="130"> </vxe-column>
          <vxe-column field="trainingType" title="培训方式" :formatter="formatterType" width="120"> </vxe-column>
          <vxe-column field="sysUserList" title="参与人员">
            <template #default="{ row }">
              <el-tag size="small"> {{ row.sysUserList && row.sysUserList.length > 0 ? row.sysUserList.map((item) => item.realname).join(',') : '' }}</el-tag>
            </template>
          </vxe-column>
        </vxe-table>
      </Pane>
    </Splitpanes>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示信息

let { proxy }: any = getCurrentInstance();
let showKnowledgeLoading = ref(false); //左侧知识库加载
let showTreeLoading = ref(false); //中间知识库树加载
let showTrainLoading = ref(false); //右侧培训加载

let knowledgeList = reactive([]); //左侧知识库数据
let knowledgeCatalogAndContentTreeData = reactive([]); //中间知识库树数据
let trainingList = reactive([]); //右侧培训数据

//中间树配置
const defaultProps = {
  children: 'children',
  label: 'name'
};
//中间树当前选中节点
let currentTreeNode = reactive({
  id: '',
  code: '',
  pid: '',
  orgId: '',
  name: '',
  seq: 0,
  status: 0,
  knowledgeId: '',
  children: {}
});
const typeOptions = reactive([
  {
    name: '线下培训',
    value: 0
  },
  {
    name: '线上培训',
    value: 1
  }
]);
let currentKnowledge = reactive({
  id: '',
  name: '',
  code: ''
});

// 方法定义区 =============================================================
onMounted(() => {
  getKnowledgeList();
});

// 获取左侧知识库列表
function getKnowledgeList() {
  showKnowledgeLoading.value = true;
  knowledgeList.length = 0;
  const url = '/api/wk/wkKnowledge/findKnowledgeList';
  proxy.$http
    .get(url)
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        knowledgeList.push(...res.data);
        currentChangeEvent({ row: knowledgeList[0] });
        const $xTable = proxy.$refs.trainingUserTableRef as any;
        if ($xTable) {
          $xTable.setCurrentRow(knowledgeList[0]);
        }
      }
      showKnowledgeLoading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      showKnowledgeLoading.value = false;
    });
}

// 获取中间目录与结果树
function getKnowledgeCatalogAndContentTree() {
  showTreeLoading.value = true;
  knowledgeCatalogAndContentTreeData.length = 0;
  const url = '/api/wk/wkKnowledgeCatalog/getKnowledgeCatalogAndContentTree/' + currentKnowledge.id;
  proxy.$http
    .get(url)
    .then((res: any) => {
      if (res.status.code !== 1) {
        proxy.$alert(res.status.msg, '提示');
      } else {
        knowledgeCatalogAndContentTreeData.push({
          id: currentKnowledge.id,
          name: currentKnowledge.name,
          code: currentKnowledge.code,
          knType: 'knowledge',
          level: 0,
          children: []
        });
        knowledgeCatalogAndContentTreeData[0].children.push(...res.data);
        if (knowledgeCatalogAndContentTreeData.length > 0) {
          currentTreeNode = findLeafNodes(knowledgeCatalogAndContentTreeData[0])[0];
          let $xtable = proxy.$refs.leftTree;
          if ($xtable) {
            proxy.$nextTick(() => {
              proxy.$refs.leftTree.setCurrentKey(currentTreeNode.id);
              handleNodeClick(currentTreeNode);
            });
          }
        }
        showTreeLoading.value = false;
      }
    })
    .catch((err: any) => {
      VxeMessage('获取机构失败', VxeNotifyType.error);
      showTreeLoading.value = false;
    });
}

// 获取右侧培训列表信息
function getTrainingList(row: any) {
  showTrainLoading.value = true;
  trainingList.length = 0;
  const url = '/wk/training/plan/getTrainingListByKnowledgeId/' + row.id;
  proxy.$http
    .get(url)
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        trainingList.push(...res.data);
        const $xTable = proxy.$refs.trainingTableRef as any;
        if ($xTable) {
          $xTable.setCurrentRow(trainingList[0]);
        }
      }
      showTrainLoading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      showTrainLoading.value = false;
    });
}

//左侧知识库点击当前行事件
function currentChangeEvent(row: any) {
  Object.assign(currentKnowledge, row.row);
  getKnowledgeCatalogAndContentTree();
}

// 点击中间树节点
function handleNodeClick(data: any) {
  getTrainingList(data);
}

// 递归函数，用于查找树形结构中的叶子节点（即没有子节点的节点）
function findLeafNodes(node) {
  if (node.children.length === 0) {
    return [node];
  }
  return node.children.reduce((leafNodes, child) => {
    return leafNodes.concat(findLeafNodes(child));
  }, []);
}

// 格式化培训方式 根据数值返回名字
function formatterType({ cellValue }) {
  const item = typeOptions.find((item) => item.value === cellValue);
  return item ? item.name : '';
}
</script>

<style lang="scss" scoped>
#trainingKnowledgeList {
  width: 100%;
  height: 100%;
  .area {
    background-color: $base-white;
    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }
    .trainingBox {
      height: calc(100% - 40px);
    }
  }
}
</style>
